/**
 * 企业搜索
 * @author  Jello
 * @create  2018/10/23 15:23
 * @version 1.0
 * @company 广东蓝聘科技网络有限公司
 **/

$(function() {
	/*搜索记录相关*/
	//从localStorage获取搜索时间的数组
	var hisTime;
	//从localStorage获取搜索内容的数组
	var hisItem;
	//从localStorage获取最早的1个搜索时间
	var firstKey;
	if(hisItem == null) {
		$(".sea_null").css("display", "block");
	}

	function init() {
		//每次执行都把2个数组置空
		hisTime = [];
		hisItem = [];
		//模拟localStorage本来有的记录
		//localStorage.setItem("a",12333);
		//本函数内的两个for循环用到的变量
		var i = 0
		for(; i < localStorage.length; i++) {
			if(!isNaN(localStorage.key(i))) {
				hisItem.push(localStorage.getItem(localStorage.key(i)));
				hisTime.push(localStorage.key(i));
				$(".sea_null").css("display", "none");
			}
		}
		i = 0;
		//执行init(),每次清空之前添加的节点
		$(".sea_his").html("");
		for(; i < hisItem.length; i++) {
			$(".sea_his").prepend('<div class="his_de">' + hisItem[i] + '</div>')
		}
	}
	init();

	//搜索的点击事件 
	document.getElementById("search").addEventListener("tap", function(e) {
		var id_num = $("#companyKey").val();
		var time = (new Date()).getTime();
		if(id_num == null || id_num == "") {
			mui.toast("请输入你要搜索的企业名称");
			return false;
		}

		//输入的内容localStorage有记录
		if($.inArray(id_num, hisItem) >= 0) {
			for(var j = 0; j < localStorage.length; j++) {
				if(id_num == localStorage.getItem(localStorage.key(j))) {
					localStorage.removeItem(localStorage.key(j));
				}
			}
			localStorage.setItem(time, id_num);
		}
		//输入的内容localStorage没有记录
		else {
			//由于限制了只能有6条记录，所以这里进行判断
			if(hisItem.length > 10) {
				firstKey = hisTime[0]
				localStorage.removeItem(firstKey);
				localStorage.setItem(time, id_num);
			} else {
				localStorage.setItem(time, id_num)
			}
		}
		init();
		var searchUrl = encodeURI("search_result.html?companyName=" + id_num); //使用encodeURI编码
		window.location.href = searchUrl;
	});

	//清除记录功能
	$("#sea_remov").click(function() {
		var f = 0;
		for(; f < hisTime.length; f++) {
			localStorage.removeItem(hisTime[f]);
		}
		$(".sea_null").css("display", "block");
		init();
	});

	$(".sea_box .sea_box2 .sea_his").on("click", ".his_de", function() {
		var this_ch = $(this).text();
		var searchUrl2 = encodeURI("search_result.html?companyName=" + this_ch);
		window.location.href = searchUrl2;
	})

	//			//苹果手机不兼容出现input无法取值以下是解决方法
	//			$(function() {
	//				$('.word-break').click(function() {
	//					var div = $(this).text();
	//					$('#idNumber1').val(div);
	//				})
	//				//取到值以后button存储无法取值，这里强迫浏览器强行刷新可解决
	//				$('#search').click(function() {
	//					window.location.reload();
	//				})
	//			})
})

function watchInputVal() {
	var value = $("#companyKey").val().trim();
	//判断是否有输入
	if(value.length > 0) {
		$("#close").css("display", "block");
	} else {
		$("#close").css("display", "none");
	}
	document.getElementById("close").addEventListener('tap', function() {
		$("#companyKey").val("");
		watchInputVal();
	}, false);
}